<template>
  <div class="points-report">
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <!-- 积分发放统计 -->
      <el-tab-pane label="积分发放统计" name="points">
        <!-- 顶部四项指标 -->
        <el-row :gutter="20" style="margin-bottom: 16px;">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">{{ pointsData.total_points_issued || 0 }}</div>
                <div class="stat-label">累计发放积分
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 420px; line-height: 1.5;">
                      <div><strong>定义：</strong>统计期内发放给用户的积分总量</div>
                      <div><strong>计算：</strong>SUM(发放积分)</div>
                      <div><strong>来源：</strong>后端聚合（积分发放记录）</div>
                      <div><strong>筛选：</strong>受时间范围 / 商户筛选限制</div>
                    </div>
                    <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                  </el-tooltip>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">{{ pointsData.total_points_consumed || 0 }}</div>
                <div class="stat-label">累计消费积分
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 420px; line-height: 1.5;">
                      <div><strong>定义：</strong>统计期内用户实际消耗的积分总量</div>
                      <div><strong>计算：</strong>SUM(消费积分)</div>
                      <div><strong>来源：</strong>后端聚合（积分消费/扣减记录）</div>
                    </div>
                    <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                  </el-tooltip>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">{{ pointsData.active_users || 0 }}</div>
                <div class="stat-label">活跃用户
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 420px; line-height: 1.5;">
                      <div><strong>定义：</strong>统计期内存在积分相关行为的去重用户数</div>
                      <div><strong>口径：</strong>示例：发生"发放或消费积分"等任一行为视为活跃</div>
                      <div><strong>来源：</strong>后端聚合（按用户去重）</div>
                    </div>
                    <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                  </el-tooltip>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-value">{{ pointsData.average_points_per_user || 0 }}</div>
                <div class="stat-label">人均积分
                  <el-tooltip placement="top">
                    <div slot="content" style="max-width: 420px; line-height: 1.5;">
                      <div><strong>定义：</strong>统计期末用户可用积分的平均值</div>
                      <div><strong>计算：</strong>期末可用积分总量 ÷ 账户数</div>
                      <div><strong>提示：</strong>为时点指标，非累计</div>
                    </div>
                    <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                  </el-tooltip>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 图表区域 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card>
              <div slot="header">积分类型分布
                <el-popover placement="top" trigger="hover" width="420">
                  <div style="max-width: 420px; line-height: 1.5;">
                    <div><strong>定义：</strong>展示积分发放按类型的占比</div>
                    <div><strong>来源：</strong>后端聚合（按类型汇总）</div>
                  </div>
                  <i slot="reference" class="el-icon-question" style="margin-left:6px;color:#909399; cursor: pointer;"></i>
                </el-popover>
              </div>
              <div id="pointsTypeChart" style="height: 350px;"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <div slot="header">每日积分发放趋势
                <el-popover placement="top" trigger="hover" width="420">
                  <div style="max-width: 420px; line-height: 1.5;">
                    <div><strong>定义：</strong>按日统计积分发放的趋势</div>
                    <div><strong>X 轴：</strong>日期；<strong>Y 轴：</strong>积分数量</div>
                    <div><strong>来源：</strong>后端聚合（按日汇总）</div>
                  </div>
                  <i slot="reference" class="el-icon-question" style="margin-left:6px;color:#909399; cursor: pointer;"></i>
                </el-popover>
              </div>
              <div id="pointsDailyChart" style="height: 350px;"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 趋势对比 + 热门活动 -->
        <el-row :gutter="20" style="margin-top: 16px;">
          <el-col :span="12">
            <el-card>
              <div slot="header">发放 vs 消费（趋势对比）
                <el-tooltip placement="top">
                  <div slot="content" style="max-width: 480px; line-height: 1.5;">
                    <div><strong>定义：</strong>同一时间尺度下对比"发放积分量"和"消费积分量"</div>
                    <div><strong>X 轴：</strong>日期；<strong>Y 轴：</strong>积分数量</div>
                  </div>
                  <i class="el-icon-question" style="margin-left:6px;color:#909399;"></i>
                </el-tooltip>
              </div>
              <div id="pointsTrendCompareChart" style="height: 350px;"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card>
              <div slot="header">热门活动 TOP5
                <el-popover placement="top" trigger="hover" width="560">
                  <div style="max-width: 560px; line-height: 1.5;">
                    <div><strong>定义：</strong>按活动的参与与奖励等指标综合排名的前5名</div>
                    <div><strong>字段：</strong>活动名称、参与人数、奖励次数、积分成本、效果评分</div>
                    <div><strong>"效果评分"解读（当前后端口径）：</strong></div>
                    <div>• 定义：反映活动热度的简化分值，范围 0–100 分，越高越好</div>
                    <div>• 计算：效果评分 = 奖励次数 × 10，封顶 100 分（例如发出 8 次奖励 → 80 分；≥10 次 → 100 分）</div>
                    <div>• 说明：当前未引入参与/完成/成本/复访等加权因素，后续升级会同步前端文案</div>
                    <div><strong>字段解释（本模块）：</strong></div>
                    <div style="padding-left:14px;">- 参与人数：参与活动的去重用户数量</div>
                    <div style="padding-left:14px;">- 奖励次数：活动期间发出的奖励记录数量（通常指积分或等值权益发放）</div>
                    <div style="padding-left:14px;">- 积分成本：活动发放积分的总量（1 积分=¥1）；若找不到真实记录，按默认单次发放积分估算</div>
                    <div style="padding-left:14px;">- 完成率：当前后端暂用"热度分"作为占位（例如 80 → 80%），并非"完成人数/参与人数"</div>
                    <div style="padding-left:14px;">- 复访率：概念为"二次及以上参与占比"，当前后端未计算，后续上线会补充</div>
                  </div>
                  <i slot="reference" class="el-icon-question" style="margin-left:6px;color:#909399; cursor: pointer;"></i>
                </el-popover>
              </div>
              <el-table :data="(pointsData.top_campaigns || [])" border stripe :header-cell-style="{ background: '#f5f7fa' }" height="350px">
                <el-table-column prop="campaign_name" label="活动名称" min-width="160" align="center" />
                <el-table-column prop="participant_count" label="参与人数" width="100" align="center" />
                <el-table-column prop="reward_count" label="奖励次数" width="100" align="center" />
                <el-table-column prop="points_cost" label="积分成本" width="100" align="center" />
                <el-table-column prop="effectiveness_score" label="效果评分" width="110" align="center">
                  <template slot="header">
                    <span>效果评分
                      <el-popover placement="top" trigger="hover" width="520">
                        <div style="max-width: 560px; line-height: 1.5;">
                          <div><strong>定义：</strong>当前实现为"热度分"，不是综合评分</div>
                          <div><strong>计算：</strong>效果评分 = 奖励次数 × 10，最高 100 分</div>
                          <div><strong>提示：</strong>完成率字段目前显示热度百分比（示例：80 → 80%），后端计划改为"完成人数/参与人数"后会同步更新</div>
                        </div>
                        <i slot="reference" class="el-icon-question" style="margin-left:6px;color:#909399; cursor: pointer;"></i>
                      </el-popover>
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 积分消费记录 -->
      <el-tab-pane label="积分消费记录" name="consumption">
        <el-table
          :data="pointsConsumptionData"
          border
          stripe
          v-loading="consumptionLoading"
          :header-cell-style="{ background: '#f5f7fa' }"
          height="500px"
          style="width: 100%;">
          <el-table-column prop="user_id" label="用户ID" width="100" align="center" />
          <el-table-column prop="user_name" label="用户名" min-width="150" />
          <el-table-column prop="consumption_type" label="消费类型" min-width="120" align="center">
            <template slot="header">
              <span>消费类型
                <el-tooltip content="积分扣减来源（如消费奖励等）" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="points_used" label="使用积分" min-width="100" align="center">
            <template slot="header">
              <span>使用积分
                <el-tooltip content="本次扣减的积分数量" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="amount_saved" label="节省金额" min-width="100" align="center">
            <template slot="header">
              <span>节省金额
                <el-tooltip placement="top">
                  <div slot="content" style="max-width: 380px; line-height: 1.5;">
                    <div><strong>定义：</strong>本次积分抵扣的金额</div>
                    <div><strong>计算口径：</strong>1 积分 = ¥1；若后端已提供折扣金额，则以其为准</div>
                    <div><strong>示例：</strong>使用 30 积分 → 节省金额 ≈ ¥30</div>
                  </div>
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
            </template>
            <template slot-scope="scope">
              <span style="color:#E6A23C; font-weight: bold;">{{ formatAmountYuan(scope.row.amount_saved != null ? scope.row.amount_saved : (scope.row.points_used || 0)) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="consumption_time" label="消费时间" min-width="160" align="center">
            <template slot="header">
              <span>消费时间
                <el-tooltip content="积分消费发生时间" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 用户积分排行 -->
      <el-tab-pane label="用户积分排行" name="ranking">
        <el-table
          :data="pointsRankingData"
          border
          stripe
          v-loading="rankingLoading"
          :header-cell-style="{ background: '#f5f7fa' }"
          height="500px"
          style="width: 100%;">
          <el-table-column prop="rank" label="排名" width="80" align="center">
            <template slot="header">
              <span>排名
                <el-tooltip content="按当前积分降序；积分相同按累计获得优先" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="user_id" label="用户ID" width="100" align="center" />
          <el-table-column prop="user_name" label="用户名" min-width="150" />
          <el-table-column prop="current_points" label="当前积分" min-width="100" align="center">
            <template slot="header">
              <span>当前积分
                <el-tooltip content="用户当前可用积分余额" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="total_earned" label="累计获得" min-width="100" align="center">
            <template slot="header">
              <span>累计获得
                <el-tooltip content="统计期内累计获得的积分" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="total_consumed" label="累计消费" min-width="100" align="center">
            <template slot="header">
              <span>累计消费
                <el-tooltip content="统计期内累计消耗的积分" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="join_date" label="加入日期" min-width="120" align="center" />
        </el-table>
      </el-tab-pane>

      <!-- 积分分布统计 -->
      <el-tab-pane label="积分分布统计" name="distribution">
        <div v-loading="distributionLoading">
          <el-card>
            <div slot="header">积分分布数据</div>
            <div id="pointsDistributionChart" style="height: 400px;"></div>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { nfcReportsAPI } from '@/api/nfc'
import ChartMixin from '../mixins/ChartMixin'

export default {
  name: 'PointsReport',
  mixins: [ChartMixin],
  props: {
    filters: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      activeTab: 'points',
      
      // 积分数据
      pointsData: {},
      pointsConsumptionData: [],
      pointsRankingData: [],
      
      // 加载状态
      consumptionLoading: false,
      rankingLoading: false,
      distributionLoading: false,
      
    }
  },
  watch: {
    filters: {
      handler() {
        this.loadCurrentTabData()
      },
      deep: true
    }
  },
  mounted() {
    this.loadCurrentTabData()
  },
  methods: {

    // 标签页切换
    async handleTabClick() {
      await this.loadCurrentTabData()
    },

    // 根据当前标签页加载数据
    async loadCurrentTabData() {
      try {
        if (this.activeTab === 'points') {
          await this.loadPointsData()
        } else if (this.activeTab === 'consumption') {
          await this.loadPointsConsumptionData()
        } else if (this.activeTab === 'ranking') {
          await this.loadPointsRankingData()
        } else if (this.activeTab === 'distribution') {
          await this.loadPointsDistributionData()
        }
      } catch (error) {
        console.error('加载积分报表数据失败：', error)
        this.$message.error('加载数据失败')
      }
    },

    // 加载积分发放统计数据
    async loadPointsData() {
      const params = { 
        ...this.filters,
        report_type: 'points' 
      }
      const response = await nfcReportsAPI.getPointsReport(params)
      const data = response.data || {}

      // 保存积分数据用于图表渲染
      this.pointsData = data

      this.$nextTick(() => {
        this.renderPointsCharts(data)
      })
    },

    // 加载积分消费记录
    async loadPointsConsumptionData() {
      try {
        this.consumptionLoading = true
        const params = {
          ...this.filters,
          report_type: 'consumption'
        }
        const res = await nfcReportsAPI.getPointsReport(params)
        console.log('积分消费统计响应:', res)

        if (res && res.code === 0 && res.data && res.data.consumption_data) {
          this.pointsConsumptionData = res.data.consumption_data
        } else {
          this.pointsConsumptionData = []
        }
      } catch (error) {
        console.error('加载积分消费统计失败:', error)
        this.$message.error('加载积分消费数据失败')
        this.pointsConsumptionData = []
      } finally {
        this.consumptionLoading = false
      }
    },

    // 加载用户积分排行
    async loadPointsRankingData() {
      try {
        this.rankingLoading = true
        const params = {
          ...this.filters,
          report_type: 'ranking'
        }
        const res = await nfcReportsAPI.getPointsReport(params)
        console.log('用户积分排行响应:', res)

        if (res && res.code === 0 && res.data && res.data.ranking_data) {
          this.pointsRankingData = res.data.ranking_data
        } else {
          this.pointsRankingData = []
        }
      } catch (error) {
        console.error('加载用户积分排行失败:', error)
        this.$message.error('加载积分排行数据失败')
        this.pointsRankingData = []
      } finally {
        this.rankingLoading = false
      }
    },

    // 加载积分分布统计
    async loadPointsDistributionData() {
      try {
        this.distributionLoading = true
        const params = {
          ...this.filters,
          report_type: 'distribution'
        }
        const res = await nfcReportsAPI.getPointsReport(params)
        console.log('积分分布统计响应:', res)
        
        if (res && res.code === 0 && res.data) {
          // 后端返回结构：{ distribution: [{label, count}], total_accounts }
          const dist = Array.isArray(res.data.distribution) ? res.data.distribution : []
          const total = Number(res.data.total_accounts || 0)
          this.pointsDistributionData = dist.map(item => {
            const count = Number(item.count || 0)
            const percentage = total > 0 ? ((count / total) * 100).toFixed(2) + '%' : '0%'
            return {
              // 表格字段映射
              range: item.label || '',
              user_count: count,
              percentage,
              // 后端未提供平均积分，先留空
              avg_points: null
            }
          })
          
          // 渲染饼图
          this.$nextTick(() => {
            this.renderChart('pointsDistributionChart', {
              title: { text: '' },
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
              },
              series: [{
                name: '积分分布',
                type: 'pie',
                data: dist.map(item => ({ name: item.label, value: item.count })),
                radius: '70%',
                label: {
                  show: true,
                  formatter: '{b}: {d}%'
                },
                labelLine: {
                  show: true
                }
              }]
            })
          })
        } else {
          this.pointsDistributionData = []
        }
      } catch (error) {
        console.error('加载积分分布统计失败:', error)
        this.$message.error('加载积分分布数据失败')
        this.pointsDistributionData = []
      } finally {
        this.distributionLoading = false
      }
    },

    // 渲染积分图表
    renderPointsCharts(data) {
      // 积分类型分布
      this.renderChart('pointsTypeChart', {
        title: { text: '' },
        series: [{
          type: 'pie',
          data: data.type_distribution || [],
          radius: '70%'
        }]
      })

      // 每日积分发放趋势
      this.renderChart('pointsDailyChart', {
        title: { text: '' },
        xAxis: { type: 'category', data: data.daily_dates || [] },
        yAxis: { type: 'value' },
        series: [{
          name: '发放',
          data: data.daily_values || [],
          type: 'line',
          smooth: true,
          areaStyle: {},
          itemStyle: { color: '#409EFF' }
        }]
      })

      // 发放 vs 消费 对比
      const compareSeries = []
      compareSeries.push({ 
        name: '发放', 
        type: 'line', 
        smooth: true, 
        data: data.daily_values || [], 
        itemStyle: { color: '#409EFF' } 
      })
      if (Array.isArray(data.trends) && data.trends.length > 0) {
        const consumed = (data.trends || []).map(i => i.consumed)
        compareSeries.push({ 
          name: '消费', 
          type: 'line', 
          smooth: true, 
          data: consumed, 
          itemStyle: { color: '#F56C6C' } 
        })
      }
      this.renderChart('pointsTrendCompareChart', {
        title: { text: '' },
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: data.daily_dates || [] },
        yAxis: { type: 'value' },
        legend: { data: compareSeries.map(s => s.name) },
        series: compareSeries
      })
    },

    // 格式化金额显示
    formatAmountYuan(amount) {
      const num = Number(amount || 0)
      return `¥${num.toFixed(2)}`
    }

  }
}
</script>

<style scoped>
.points-report {
  padding: 0;
}

.stat-card {
  height: 120px;
}

.stat-content {
  text-align: center;
  padding: 20px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

/* 表格样式 */
.points-report .el-table {
  width: 100% !important;
}

/* 标签页内容样式 */
.points-report .el-tabs__content {
  padding-left: 0;
  padding-right: 0;
}
</style>